package org.scau.weibo.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.scau.weibo.dao.BaseDAO;
import org.scau.weibo.dao.IUserDAO;
import org.scau.weibo.vo.BUser;

public class UserDAO extends BaseDAO implements IUserDAO{

	@Override
	public void saveUser(BUser user) {
		
		Session session=getSession();
		Transaction tx=session.beginTransaction();
		if (validateUserEmail(user.getUserEmail())||validateUserName(user.getUserName())) {
			session.close();
		}
		else{
			session.save(user);
			tx.commit();
			session.close();	
		}
	}

	@Override
	public BUser validateUser(String userEmail, String password) {
		
		Session session=getSession();
		String hql="from BUser u where u.userEmail=? and u.userPwd=?";
		Query query=session.createQuery(hql);
		query.setParameter(0, userEmail);
		query.setParameter(1, password);
		List<?> users=query.list();
		if(users.size()!=0){
			BUser user=(BUser)users.get(0);
			return user;
		}
		session.close();
		return null;
	}

	@Override
	public boolean validateUserEmail(String userEmail) {
		
		Session session=getSession();
		String hql="from BUser u where u.userEmail=?";
		Query query=session.createQuery(hql);
		query.setParameter(0, userEmail);
		List<?> users=query.list();
		if(users.size()!=0){
			return true;
		}
		session.close();
		return false;
	}

	@Override
	public boolean validateUserName(String username) {
		
		Session session=getSession();
		String hql="from BUser u where u.userName=?";
		Query query=session.createQuery(hql);
		query.setParameter(0, username);
		List<?> users=query.list();
		if(users.size()!=0){
			return true;
		}
		session.close();
		return false;
	}

	@Override
	public void updateUser(BUser user) {
		
		Session session=getSession();
		Transaction tx=session.beginTransaction();
		session.update(user);
		tx.commit();
		session.close();		
	}

}
